package com.merry.mq.springBoot.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author msi
 * ttl队列的配置类
 */

@Configuration
public class TtlQueueConfig {

    //普通交换机的名称
    public static String X_EXCHANGE = "X";
    //死信交换机的名称
    public static String Y_DEAD_LETTER_EXCHANGE = "Y";
    //普通队列的名称
    public static final String A_QUEUE = "QA";
    public static final String B_QUEUE = "QB";
    //死信队列的名称
    public static final String D_QUEUE = "QD";

    //声明xExchange 的别名
    @Bean("xExchange")
    public DirectExchange xExchange(){
        return new DirectExchange(X_EXCHANGE);
    }

    //声明yExchange 的别名
    @Bean("yExchange")
    public DirectExchange yExchange(){
        return new DirectExchange(Y_DEAD_LETTER_EXCHANGE);
    }

    //声明普通队列 要有并设置ttl为10s
    @Bean("queueA")
    public Queue queueA(){
        Map<String ,Object> args=new HashMap<>(3);
        //设置死信交换机
        args.put("x-dead-letter-exchange",Y_DEAD_LETTER_EXCHANGE);
        //设置死信routingkey
        args.put("x-dead-letter-routing-key","YD");
        //设置ttl时间
        args.put("x-message-ttl",10000);
        return QueueBuilder.durable(A_QUEUE).withArguments(args).build();
    }

    //声明普通队列 要有并设置ttl为40s
    @Bean("queueB")
    public Queue queueB(){
        Map<String ,Object> args=new HashMap<>(3);
        //设置死信交换机
        args.put("x-dead-letter-exchange",Y_DEAD_LETTER_EXCHANGE);
        //设置死信routingkey
        args.put("x-dead-letter-routing-key","YD");
        //设置ttl时间
        args.put("x-message-ttl",40000);
        return QueueBuilder.durable(B_QUEUE).withArguments(args).build();
    }

    //声明死信队列
    @Bean("queueD")
    public Queue queueD(){
        return QueueBuilder.durable(D_QUEUE).build();
    }

    //声明交换机和队列的绑定关系
    @Bean
    public Binding queueABindingX(@Qualifier("queueA") Queue queueA,
                                  @Qualifier("xExchange") DirectExchange xExchange){
        return BindingBuilder.bind(queueA).to(xExchange).with("XA");
    }

    @Bean
    public Binding queueBBindingX(@Qualifier("queueB") Queue queueB,
                                  @Qualifier("xExchange") DirectExchange xExchange){
        return BindingBuilder.bind(queueB).to(xExchange).with("XB");
    }

    @Bean
    public Binding queueDBindingY(@Qualifier("queueD") Queue queueD,
                                  @Qualifier("yExchange") DirectExchange yExchange){
        return BindingBuilder.bind(queueD).to(yExchange).with("YD");
    }
}
